package org.zjx.core;

import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.zjx.listener.EventListener;
import org.zjx.task.core.ITaskChain;
import org.zjx.task.core.TaskScheduler;
import org.zjx.window.GameWindow;
import org.zjx.window.WindowManager;

import java.awt.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Getter
@Setter
public class GameThread implements Runnable {
    private GameWindow window;
    private TaskManager taskManager;
    private WindowManager windowManager;
    private GameContext gameContext;

    private boolean running = true;
    private AtomicBoolean needAssistant = new AtomicBoolean(false);

    private EventListener eventListener = o -> {
        if (!TaskScheduler.NO_TASK_VALUE.equals(o)) return;
        needAssistant.set(true);
    };


    public GameThread(Point point, WindowManager windowManager) {
        window = new GameWindow(point);
        this.windowManager = windowManager;
        gameContext = new GameContext();
        gameContext.addListener(TaskScheduler.class.getSimpleName(), eventListener);
        new GameInstance.Builder().gameContext(gameContext).gameThread(this).build();
        this.taskManager = new TaskManager(GameInstance.getInstance());
    }

    @SneakyThrows
    @Override
    public void run() {
        windowManager.launchGame(this);
        while (running) {
            assistant();
        }
    }

    public void assistant() {
        if (!needAssistant.get()) return;
        List<ITaskChain> chains = taskManager.getChains("chain/chain-main.txt");
        taskManager.add(chains);
        needAssistant.set(false);
    }

    public void outGame() {
        System.out.println("游戏结束");
    }
}
